import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2024-03-09
 * Time: 18:01
 */
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取到用户名和密码
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        if(userName == null || password == null || userName.equals("") || password.equals("")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("请求的参数不完整！！");
            return;
        }

        //2.验证用户密码是否正确
        if (!userName.equals("root")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名错误");
            return;
        }
        if (!password.equals("000")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户密码错误！！");
            return;
        }

        //3.用户登录成功！！ 此时就可以给这个用户创建会话了。
        HttpSession session = req.getSession(true);

        //在会话中保存自定义的数据
        session.setAttribute("time",System.currentTimeMillis());
        session.setAttribute("username",userName);

        // 让页面自动跳转
        //用servlet生成一个动态页面
        resp.sendRedirect("index");
    }
}
